package com.weapons.week0903_weapons.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import com.weapons.week0903_weapons.R;
import com.weapons.week0903_weapons.constant.UrlString;
import com.weapons.week0903_weapons.utils.NetUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Author: Administrator
 * Created by Administrator on 2016/7/21.
 */
public class ImageShowActivity extends AppCompatActivity{
    private ViewPager vp;
    private TextView tv,tv1;
    private ProgressDialog dialog;
    private NewImageShowAdapter ivAdapter;
    private List<View> mView;
    private OkHttpClient mClient;
    private List<String> mArr,mUri;
    private int currentIndex;
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imageshow);
        vp = (ViewPager) findViewById(R.id.showimage_vp);
        tv = (TextView) findViewById(R.id.imageshow_tv);
        tv1 = (TextView) findViewById(R.id.imageshow_bottomtv);
        Intent intent = getIntent();
        mArr = new ArrayList<>();
        mUri = new ArrayList<>();
        String uriId = intent.getStringExtra("image");
        String text = intent.getStringExtra("image1");
        String url = String.format(UrlString.URL_IMAGEPAGER,uriId);
        initData(url);
        ivAdapter = new NewImageShowAdapter();
        tv1.setText(text);
        vp.setAdapter(ivAdapter);
        vp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            public void onPageSelected(int position) {
                currentIndex = position;
                tv.setText((position+1)+"/"+mUri.size());
            }
            public void onPageScrollStateChanged(int state) {
            }
        });
    }
    private void initData(String url) {
        mClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        mClient.newCall(request).enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {

            }
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                mArr = Arrays.asList(str.split("\""));
                runOnUiThread(new Runnable() {
                    public void run() {
                        mUri.clear();
                        for(String s:mArr){
                            if(s.endsWith(".jpg")){
                                String s1 = s.replace("\\/","/");
                                mUri.add(s1);
                            }
                        }
                        mUri.remove(0);
                        ivAdapter.notifyDataSetChanged();
                    }
                });
            }
        });
    }
    private class NewImageShowAdapter extends PagerAdapter{
        public int getCount() {
            return mUri==null? 0:mUri.size();
        }
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView iv = new ImageView(ImageShowActivity.this);
            DisplayMetrics dm = getResources().getDisplayMetrics();
            Picasso.with(ImageShowActivity.this).load(mUri.get(position)).resize(dm.widthPixels,dm.heightPixels-500)
                    .into(iv);
            container.addView(iv);
            return iv;
        }
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View)object);
        }
    }

    public void btn_Return(View view){
        switch (view.getId()){
            case R.id.imageshow_ibt:
                finish();
                break;
            case R.id.imageshow_ibt1:
                ShareSDK.initSDK(this,"15376e9464ad2");
                showShare();
                break;
            case R.id.imageshow_bottombt:
                dialog = new ProgressDialog(ImageShowActivity.this);
                dialog.setTitle("正在下载图片");
                dialog.setIcon(R.drawable.progress_bar_icon);
                dialog.setCancelable(false);
                dialog.show();
                new Imageloader().execute(mUri.get(currentIndex));
        }
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
//关闭sso授权
        oks.disableSSOWhenAuthorize();

// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
        oks.setTitle("标题");
// titleUrl是标题的网络链接，QQ和QQ空间等使用
        oks.setTitleUrl("http://www.xinjunshi.com/");
        oks.setImageUrl(mUri.get(currentIndex));
// text是分享文本，所有平台都需要这个字段
        oks.setText("分享内容");
// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
// url仅在微信（包括好友和朋友圈）中使用
        // oks.setUrl("http://sharesdk.cn");
// comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("评论文本");
// site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
// siteUrl是分享此内容的网站地址，仅在QQ空间使用
        //   oks.setSiteUrl("http://www.xinjunshi.com/");
// 启动分享GUI
        oks.show(this);
    }

    private class Imageloader extends AsyncTask<String,Object,Bitmap>{
        protected Bitmap doInBackground(String... params) {
            try {
                byte[] buf =  NetUtils.getDataByBytes(params[0]);
                Bitmap bmp = BitmapFactory.decodeByteArray(buf,0,buf.length);
                File filepath = new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/Pictures");
                if (!filepath.exists()){
                    filepath.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory().getAbsoluteFile()+"/Pictures/"+System.currentTimeMillis()+".jpg"));
                bmp.compress(Bitmap.CompressFormat.JPEG,100,fos);
                fos.close();
                return bmp;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if(dialog != null){
                dialog.dismiss();
            }
        }
    }
}
